import http from "./request.js"
let login =  (code) => {
	let userParams = {}
	let params = {}
	uni.getUserInfo({
		success:async function(res) {
			setStorage('userInfo', res.userInfo)
			userParams = {
				iv: res.iv,
				rawData: res.rawData,
				signature: res.signature,
				encryptedData: res.encryptedData
			}
			params = Object.assign(userParams, {
				code: code
			})
			let resp = await http.post({
				url: '/auth/wechat/code',
				data: params
			})
			setStorage('Authorization', resp.result)
			uni.redirectTo({
				url: '/pagesLogin/loginRegister/bindAccount',
				fail(e){
					console.log(e)
				},
				success(e){
					console.log(e)
				}
			})


			//-----------------------
			// http.request('/auth/wechat/code', 'POST', params, {
			// 	'content-type': "application/x-www-form-urlencoded"
			// }).then(e => {
			// 	setStorage('Authorization', e.data.result)
			// 	uni.navigateTo({
			// 		url: '/pages/loginRegister/bindAccount',
			// 	})
			// }).catch(e => {
			// 	uni.showToast({
			// 		title: "登录失败！",
			// 		icon: "none"
			// 	})
			// })
			// ---------------


		}
	})
}

let getStorage = (key) => {
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: key,
			success: function(res) {
				resolve(res.data)
			},
			fail: function(e) {
				reject(e)
			}
		});
	})
}

// let getStorage =async (key) => {
// 	console.log(uni.getStorage({
// 			key: key,
// 			success: function(res) {
// 				return(res.data)
// 			},
// 			fail: function(e) {
// 				return(false)
// 			}
// 		}))
// 	return	uni.getStorage({
// 			key: key,
// 			success: function(res) {
// 				return(res.data)
// 			},
// 			fail: function(e) {
// 				return(false)
// 			}
// 		});
	
// }

let setStorage = (key, val) => {
	return new Promise((resolve, reject) => {
		uni.setStorage({
			key: key,
			data: val,
			success: function(res) {
				resolve(res)
			},
			fail: function(e) {
				reject(e)
			}
		});
	})
}
let getSetting = (scope) => {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success(res) {
				if (res.authSetting[scope]) {
					resolve(true)
				} else {
					reject(false)
				}
			},
			fail(res) {
				reject(false)
			}
		})
	})
}


let uniLogin = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			success(res) {
				resolve(res.code)
			}
		})
	})
}
let checkSession = () => {
	return new Promise((resolve, reject) => {
		uni.checkSession({
			success(res) {
				resolve(true)
			},
			fail(res) {
				reject(false)
			}
		})
	})
}
let removeStorage = (key) => {
	return new Promise((resolve, reject) => {
		uni.removeStorage({
			key: key,
			success: function(res) {
				resolve(res)
			}
		});
	})
}

export default {
	login,
	getStorage,
	setStorage,
	getSetting,
	uniLogin,
	checkSession,
	removeStorage
}
